﻿using DataCollection.Core.Models;
using DataCollection.Infrastructure;
using DataCollection.WinForm.ViewModel;
using Dm;
using Mapster;

namespace DataCollection.WinForm.Forms
{
    public partial class ManageDeviceForm : DCBaseForm
    {
        #region 属性
        private DevicePointViewModel devicePointViewModel = null!;

        private DeviceViewModel deviceViewModel = null!;
        /// <summary>
        /// 选择的设备
        /// </summary>
        private DeviceItem? SelectedDeviceItem;

        /// <summary>
        /// 选择的点位
        /// </summary>
        private DevicePointItem? SelectedDevicePointItem;

        public int Type;
        #endregion

        #region 自定义方法

        /// <summary>
        /// 布局
        /// </summary>
        private void SetupForm()
        {
            DeviceTable.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("Number","编号",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Name","名称",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("SlaveAddress","地址",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("PortAddress","串口",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Baudrate","波特率",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Enable","状态",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Register","点位",AntdUI.ColumnAlign.Center)
            };

            PointTable.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("Number","点位编号",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Name","点位名称",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Address","点位地址",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("PointType","点位类型",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Range","量程范围",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Out","输出范围",AntdUI.ColumnAlign.Center),
            };

            DCSplitter1.Panel1MinSize = (int)Math.Ceiling(550 * AntdUI.Config.Dpi);
        }

        /// <summary>
        /// 设备列表
        /// </summary>
        public void LoadDeviceList()
        {
            Dictionary<string, object> where = new Dictionary<string, object>();
            List<DeviceModel> list = DeviceModel.List(where);
            List<DeviceItem> itemList = new List<DeviceItem>();
            foreach (DeviceModel model in list)
            {
                DeviceItem item = new DeviceItem();
                model.Adapt(item);
                itemList.Add(item);
            }
            DeviceTable.DataSource = itemList;
        }

        /// <summary>
        /// 设备点位列表
        /// </summary>
        public void LoadDevicePointList()
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            if (SelectedDeviceItem is not null)
            {
                where["device_number"] = SelectedDeviceItem.Number;
            }
            List<DevicePointModel> list = DevicePointModel.List(where);
            List<DevicePointItem> itemList = new List<DevicePointItem>();
            foreach (DevicePointModel model in list)
            {
                DevicePointItem item = new DevicePointItem();
                model.Adapt(item);
                itemList.Add(item);
            }
            PointTable.DataSource = itemList;
        }

        #endregion

        #region 系统方法
        public ManageDeviceForm()
        {
            InitializeComponent();
            FullScreen = true;
            if (Type == 0)
            {
                Header.Text = "设备管理";
            }
            else
            {
                Header.Text = "选择点位";
            }
        }

        private void ManageDeviceForm_Load(object sender, EventArgs e)
        {
            SetupForm();
            DCSpin(this, "加载数据...", (action) =>
            {
                LoadDeviceList();
                LoadDevicePointList();
            }, null, () => { });
        }

        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceAddButton_Click(object sender, EventArgs e)
        {
            AddDeviceForm frm = new AddDeviceForm();
            frm.Owner = this;
            frm.ShowDialog();
        }
        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceDeleteButton_Click(object sender, EventArgs e)
        {
            if (SelectedDeviceItem == null)
            {
                ErrorNotification("请选择设备");
                return;
            }
            Dictionary<string, object> where = new Dictionary<string, object>();
            where["device_number"] = SelectedDeviceItem.Number;
            List<DevicePointModel> list = DevicePointModel.List(where);
            if (list.Count > 0)
            {
                Error(string.Format("【{0}】设备包含点位无法删除", SelectedDeviceItem.Name));
                return;
            }

            string msg = string.Format("您确定要删除【{0}】设备吗？", SelectedDeviceItem.Name);
            AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", msg)
            {
                OnOk = config =>
                {
                    deviceViewModel = new DeviceViewModel(long.Parse(SelectedDeviceItem.Number));
                    Response response = deviceViewModel.Delete();
                    if (response.Code == Response.SuccessCode)
                    {
                        Success(response.Msg);
                        LoadDeviceList();
                        SelectedDeviceItem = null;
                    }
                    else
                    {
                        Error(response.Msg);
                    }
                    return true;
                },
            });
        }

        /// <summary>
        /// 编辑设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceEditButton_Click(object sender, EventArgs e)
        {
            if (SelectedDeviceItem == null)
            {
                ErrorNotification("请选择设备");
                return;
            }

            EditDeviceForm frm = new EditDeviceForm();
            frm.Owner = this;
            frm.number = SelectedDeviceItem.Number;
            frm.ShowDialog();
        }

        /// <summary>
        /// 添加点位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PointAddButton_Click(object sender, EventArgs e)
        {
            if (SelectedDeviceItem == null)
            {
                ErrorNotification("请选择设备");
                return;
            }
            AddDevicePointForm frm = new AddDevicePointForm();
            frm.deviceItem = SelectedDeviceItem;
            frm.Owner = this;
            frm.ShowDialog();
        }

        /// <summary>
        /// 删除点位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PointDeleteButton_Click(object sender, EventArgs e)
        {
            if (SelectedDevicePointItem == null)
            {
                Error("请选择点位");
                return;
            }

            string msg = string.Format("您确定要删除【{0}】点位吗？", SelectedDevicePointItem.Name);
            AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", msg)
            {
                OnOk = config =>
                {
                    devicePointViewModel = new DevicePointViewModel(long.Parse(SelectedDevicePointItem.Number));
                    Response response = devicePointViewModel.Delete();
                    if (response.Code == Response.SuccessCode)
                    {
                        Success(response.Msg);
                        LoadDevicePointList();
                        SelectedDevicePointItem = null;
                    }
                    else
                    {
                        Error(response.Msg);
                    }
                    return true;
                },
            });
        }

        /// <summary>
        /// 编辑点位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PointEditButton_Click(object sender, EventArgs e)
        {
            if (SelectedDevicePointItem == null)
            {
                Error("请选择点位");
                return;
            }

            EditDevicePointForm frm = new EditDevicePointForm();
            frm.Owner = this;
            frm.number = SelectedDevicePointItem.Number;
            frm.ShowDialog();
        }

        private void DeviceTable_CellClick(object sender, AntdUI.TableClickEventArgs e)
        {
            if (e.Record is DeviceItem data)
            {
                SelectedDeviceItem = data;
                LoadDevicePointList();
            }
        }

        private void PointTable_CellClick(object sender, AntdUI.TableClickEventArgs e)
        {
            if (e.Record is DevicePointItem data)
            {
                SelectedDevicePointItem = data;
            }
        }
        #endregion

        private void PointTable_CellDoubleClick(object sender, AntdUI.TableClickEventArgs e)
        {
            if (Type == 1)
            {
                if (e.Record is DevicePointItem data)
                {
                    if (this.Owner is not null)
                    {
                        AddFormPointForm frm = (AddFormPointForm)this.Owner;
                        frm.SelectDevicePointItem = data;
                        this.Close();
                    }
                }
            }
        }

        private void ManageDeviceForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.Owner is not null)
            {
                AddFormPointForm frm = (AddFormPointForm)this.Owner;
                frm.LoadDevicePointInfo();
            }
        }
    }
}
